package com.wframe.project.former.web.marketing;


import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.pageform.DataPageForm;
import com.wframe.project.former.dataservices.marketing.*;
import com.wframe.project.former.dataservices.products.ProductClassService;
import com.wframe.project.former.dataservices.products.ProductService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Author on 2017/6/12.
 */
public class BuySendPromotionPage extends DataPageForm {
    private static BuySendService buySendService = BuySendService.getIntance();
    private static PromotionsService promotionsService = PromotionsService.getIntance();
    private static BuyService buyService = BuyService.getIntance();
    private ProductClassService pcservice = ProductClassService.getIntance();
    private ProductService service = ProductService.getIntance();
    private static BuyPromotionsService buyPromotionsService = BuyPromotionsService.getIntance();
    private JdataBean bean;

    @Override
    public String execute() throws Exception {
        setPagination(buyService.querybuyList(bean,getPageSize_(), getPageNum()));
        return "/webadmin/marketing/buysendList.jsp";
    }

    @Override
    public String show() throws Exception {
        bean = buySendService.selectBuySendByid(bean.getInt("id"));
        if (StringUtils.isNotBlank(bean.getString("product_val"))) {  //查询参加活动的商品信息
            JdataBean selectedPro = buySendService.querySelectedProduct(bean.getInt("product_val"));
            if(selectedPro != null) {
                //selectedPro.put("price",promotionsService.getProducrPrice(String.valueOf(selectedPro.get("id"))));
                selectedPro.put("types", promotionsService.getProductMoneyOffTypeById(String.valueOf(bean.getString("product_val"))));
                List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(selectedPro.get("id")), 1);
                for (JdataBean product : jdataBeans) {
                    selectedPro.put(product.getString("code"), product.get("val"));
                }
                selectedPro.put("classname", pcservice.getProductClassName(String.valueOf(selectedPro.getString("id"))));
                getRequest().setAttribute("selectedPro",selectedPro);
            }
        }
        getRequest().setAttribute("controlsales", promotionsService.promotionControlsale(bean.getInt("promotionid")));
        return "/webadmin/marketing/buySendListEdit.jsp";
    }

    @Override
    public String toDel() throws Exception {
        return null;
    }

    @Override
    public boolean toUpdate() throws Exception {
        try {
            JdataBean basedata = new JdataBean();
            basedata.put("platform", bean.getString("platform"));
            basedata.put("start_time", bean.getString("start_time"));
            basedata.put("end_time", bean.getString("end_time"));
            basedata.put("description", bean.getString("description"));
            basedata.put("district_description",bean.getString("district_description"));
            basedata.put("name", bean.getString("name"));
            basedata.put("show_sell",bean.getString("show_sell"));
            basedata.put("time", bean.getString("time"));
            basedata.put("sort_value", bean.getString("sort_value"));

            if (StringUtils.isNotBlank(bean.getString("product_val"))) {
                basedata.put("product_val", bean.getInt("product_val"));
                basedata.put("product_type", 1);
            }else {
                basedata.put("product_val", null);
                basedata.put("product_type", null);
            }

            Map key = new HashMap();
            key.put("id", bean.getString("promotionid"));

            //更新基础促销数据
            if (StringUtils.isNotBlank(bean.getString("promotionid"))) {
                promotionsService.update(basedata.getDataMap(), key);
            }
            //买送促销数据
            JdataBean buySendData = new JdataBean();
            buySendData.put("buy_number", bean.getString("buy_number"));
            buySendData.put("send_number", bean.getString("send_number"));
            if(StringUtils.isNotBlank(bean.getString("product_val"))){
                JdataBean productBean  = buySendService.queryproduct(bean.getInt("product_val"));
                buySendData.put("name", productBean.getString("name"));
            }
            key.put("id", bean.getInt("buysendid"));

            //更新买送促销数据
            if (StringUtils.isNotBlank(bean.getString("buysendid"))) {
                buySendService.update(buySendData.getDataMap(), key);
            }

            //更新控销数据
            if (StringUtils.isNotBlank(bean.getString("promotionid"))) {
                JSONArray controlsales = null;
                if (StringUtils.isNotBlank(bean.getString("controlsales")))
                    controlsales = new JSONArray(bean.getString("controlsales"));
                buySendService.addControlsalesSingLe(bean.getString("promotionid"), controlsales, bean.getString("controlusers"));
            }

            //保存买送促销与基本促销数据与控销数据
            if (StringUtils.isBlank(bean.getString("promotionid")) && StringUtils.isBlank(bean.getString("buysendid"))) {
                basedata.put("create_time", new Date());
                basedata.put("promotion_type", 1);
                basedata.put("weight",1);
                basedata.put("second_priority",1);
                String pid = promotionsService.addPromotions(basedata);    //保存买送促销promotions
                buySendData.put("promotionid",Integer.valueOf(pid));
                buySendService.save(buySendData.getDataMap());   //保存买送促销数据

                JSONArray controlsales = null;
                if (StringUtils.isNotBlank(bean.getString("controlsales")))
                    controlsales = new JSONArray(bean.getString("controlsales"));
                buySendService.addControlsalesSingLe(pid, controlsales, bean.getString("controlusers"));//保存控销数据
            }

            getJsonObject().put("state", "ok");
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存商品信息错误：", e);
            getJsonObject().put("state", e.getMessage());
        }
        return false;
    }

    public String buySendAdd() throws Exception {
        return "/webadmin/marketing/buySendAdd.jsp";
    }

    /**
     * 选择商品列表
     * @return
     * @throws Exception
     */
    public String chooseProductList() throws Exception {

        PageResult  pr = buySendService.queryChooseProduct(bean, 10, getPageNum());
        List<JdataBean> list = pr.getList();
        String[] productids = new String[list.size()];
        for(int i = 0 ; i < list.size() ; i++) {
            productids[i] = list.get(i).getString("id");
        }
        List<JdataBean> PromotionTypes = promotionsService.getProductPromotionTypeByIds(productids);

        for (JdataBean product : list) {
            List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(product.get("id")), 1);
            for (JdataBean attr : jdataBeans) {
//                product.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(product.get("id"))));
                for(JdataBean types : PromotionTypes) {
                    if(product.getString("id") != null && product.getString("id").equals(types.getString("id"))) {
                        product.put("moneyOffType",types.getString("pms"));
                    }
                }
                product.put(attr.getString("code"), attr.get("val"));
            }
            product.put("classname", pcservice.getProductClassName(String.valueOf(product.getString("id"))));

        }

        setPagination(pr);
        return "/webadmin/marketing/chooseProductList1.jsp";
    }

    public String BuyUpDataStop() throws Exception {
        buyPromotionsService.BuyUpDataStop(bean.getInt("promotionid"),bean.getInt("state"));
        return getJsonObject().toString();
    }

    public JdataBean getBean() {
        return bean;
    }

    public void setBean(JdataBean bean) {
        this.bean = bean;
    }
}
